/*
 * @Description: 租户信息插件
 * @Author: seadon
 * @LastEditors: zhaoxiaoyang zhaoxiaoyang@byteluck.com
 * @Date: 2021-07-08 22:23:56
 * @LastEditTime: 2024-01-12 12:07:35
 */
import store from '@/store/index'
import { apiInit } from '@/services'
import { LocaleEnum } from '@/locales'

import {
	customInit,
	ProjectType,
	TenantInitUtil,
} from '@byteluck-fe/global-shared'
import { App } from 'vue'
import pcRouter from '@/entry_desktop/router'
import { path } from '@/utils'

export default {
	async install(app: App, type: 'desktop' | 'mobile') {
		const api = apiInit()

		let user: any = {
			data: {
				// 默认先取cookies中的语言，cookies中取不到再取中文
				cookie_language_enum:
					(localStorage.getItem('locale') as any) ?? LocaleEnum.zh,
			},
		}

		// 判断是否登录
		const isLoginHref = window.location.href.indexOf('login') > -1
		if (!isLoginHref) {
			user = await api.baseAuto.GetCurrentUserEmployeePrivateV1POST({}) //新
			sessionStorage.setItem('userInfoData', JSON.stringify(user.data))
			// 外部组织没选择部门的跳转
			if (!user.data) {
				location.href = path.getFullPath(
					`/login.html?redirect_uri=${encodeURIComponent(
						window.location.href
					)}&login_status=external_org_login`
				)
			}
			//数据处理
			if (user.data.sys_admin) {
				user.data.sys_admin = true
				user.data.app_admin = true
				user.data.manage_admin = true
			} else if (user.data.external_user !== true) {
				user.data.sys_admin = false //处理1
				if (user.org_type !== 'EXTERNAL') {
					const isAppAdmin = await api.default.IsAppAdminUserPrivateV2GET({}) //处理2
					user.data.app_admin = isAppAdmin?.data //处理2
				}
				const isManageAdmin = await api.default.IsManageAdminUserPrivateV2GET(
					{}
				) //处理3
				user.data.manage_admin = isManageAdmin.data //处理3
			}
			store.commit('setUserInfo', user.data)
		}
		let tenantDetail: any =
			await api.baseAuto.GetTenantDetailTenantPublicApiPOST({})
		if (tenantDetail.data.tenant_auth.external_org) {
			const outsideOrgList = await api.baseAuto.AllExternalMulPublicApiPOST({
				query: {
					tenantId: tenantDetail.data.tenant_id,
				},
			})
			store.commit('setOutsideOrgRegisterList', outsideOrgList.data)
		}

		// if (
		// 	!isLoginHref &&
		// 	tenantDetail.data.tenant_auth.baiteda_security_account &&
		// 	!(user.data.org_type === 'EXTERNAL')
		// ) {
		// 	const userCenter = await api.default.GetCenterUserUserCenterPrivateV1GET(
		// 		{}
		// 	)
		// 	store.commit('setCenterUser', userCenter.data)
		// 	localStorage.userCenter = JSON.stringify(userCenter.data)

		// 	if (
		// 		user.data?.employee_id !== 'sysadmin' &&
		// 		tenantDetail.data.login_types === '0' &&
		// 		!tenantDetail.data.is_private_environment &&
		// 		tenantDetail.data.env_type === 'prd' &&
		// 		tenantDetail.data.tenant_auth.baiteda_security_account &&
		// 		!userCenter.data?.user_base_info &&
		// 		!(user.data.org_type === 'EXTERNAL')
		// 	) {
		// 		pcRouter.push('/welcome')
		// 	}
		// }

		// const appLauncher = tenantDetail.data.tenant_auth?.app_launcher
		// if (appLauncher) {
		// 	window.location.href = path.getFullPath('/apps/desktop/multipleTabs')
		// }
		const portal_script =
			tenantDetail?.data?.tenant_custom_config_map?.portal_script
		if (portal_script) {
			await customInit(portal_script, app, type)
		}

		// 初始化租户信息
		const TenantUtil = new TenantInitUtil(
			tenantDetail,
			user,
			ProjectType.Portal
		)
		tenantDetail = TenantUtil.initTenant(tenantDetail)
		store.commit('setTenant', tenantDetail.data)

		// 主题色刷新
		void TenantUtil.comparisonTheme()
		// 因为主题实时刷新问题，在这里存储租户详情，不用再次调用请求更新
		localStorage.tenantDetail = JSON.stringify(tenantDetail)

		// 登录页面返回，不执行后续操作
		if (isLoginHref) {
			return
		}
		if (
			!isLoginHref &&
			tenantDetail.data.tenant_auth.baiteda_security_account &&
			!(user.data.org_type === 'EXTERNAL')
		) {
			const userCenter = await api.default.GetCenterUserUserCenterPrivateV1GET(
				{}
			)
			store.commit('setCenterUser', userCenter.data ?? {})
		}

		// 添加水印
		void TenantUtil.addWaterMark()
		// qiyu 2021-10-29 --task=1004337 --user=戚雨 【私有化环境】增加空文件用来存放私有化本地信息 https://www.tapd.cn/67265839/s/1148189
		void TenantUtil.customMethod()
		// 产品要求 先用‘运行态界面’埋点
		window.BaiteTrack = TenantUtil.addTrackingData({
			sensors: { name: '运行态界面' },
		})

		// 更新租户信息的本地存储
		// void TenantUtil.updateLocalStorage(
		// 	api.baseAuto.GetTenantDetailTenantPublicApiPOST.bind(api.baseAuto),
		// 	isLocalTenant,
		// 	tenantDetail,
		// 	store
		// )
	},
}
